//请求的地址
export const HTTP = "https://apishop.qiancdj.com/api/";
//提示语
import st from "@/utils/showtoast.js";
import AppSocket from "@/utils/webSocket.js";

/**
 * 网络请求
 * @param {'GET' | 'POST'} method 请求的方式
 * @param {String} url 请求的地址
 * @param {Object} data 请求的参数
 */
export const request = (method, url, data = {}) => {
	uni.showLoading({
		title: "请求中",
		mask: true
	})
	return new Promise((success, fail) => {
		let token = uni.getStorageSync('userInfo')['shop_token'] || ""
		uni.request({
			url: HTTP + url,
			method: method,
			header: {
				token: token
			},
			data: data,
			success: res => {
				uni.hideLoading()
				uni.stopPullDownRefresh()
				let model = res.data
				console.log("打印一下请求的相关数据", data, url, token, res);
				if (model.code == 1) {
					success(model)
				} else if (model.code == 5) {
					AppSocket.onBing(() => {
						request(method, url, data)
					})
				} else {
					st.show(model.msg)
					fail(model)
				}
			},
			fail: res => {
				uni.hideLoading()
				uni.stopPullDownRefresh()
				st.show("服务器请求失败，请稍后重试")
			}
		})
	})
}

export let upload = (file) => {
	uni.showLoading({
		title: "上传中",
		mask: true
	})
	let promise = new Promise((success, fail) => {
		uni.uploadFile({
			filePath: file,
			name: "file",
			url: HTTP + "common/upload",
			success(res) {
				uni.hideLoading()
				// console.log("上传文件", res);
				if (res.errMsg == "uploadFile:ok") {
					let data = JSON.parse(res.data)
					if (data.code == 1) {
						success(data)
					} else {
						fail(data)
					}
				}
			},
			fail: res => {
				uni.hideLoading()
			},
		})
	})
	return promise
}


module.exports = {
	request,
	upload
}